package com.prj.ufdm.web.security.branch;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.prj.ufdm.web.bpo.SysUserBPO;
import com.prj.ufdm.web.enums.WebRetCodeEnum;
import com.prj.ufdm.web.model.SysUser;
import com.prj.ufdm.core.dto.RetData;
import com.prj.ufdm.core.util.UfdmDateUtil;
import com.prj.ufdm.core.util.UfdmRequestUtil;
import com.prj.ufdm.core.util.UfdmUUIDUtil;

/**
 * 用户名、密码登录成功后处理（设置TOKEN）
 * @author 胡义振  
 * @date 2018年3月22日
 */
@Service
public class LoginSuccessHandle extends SimpleUrlAuthenticationSuccessHandler{
	
	@Autowired
	SysUserBPO sysUserBPO;
	
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,HttpServletResponse response, Authentication authentication)	throws IOException, ServletException {
		RetData<Map<String,Object>> retData = new RetData<>();
		// 获取登录用户信息
		SysUser sysUser = (SysUser) authentication.getPrincipal();
		
		if(sysUser!=null) {
			try {
				
				// 生成token
				String generateToken = UfdmUUIDUtil.getUUID();
				// token 生成时间
				String tokenCreateTime = UfdmDateUtil.getCurrentTime();
				sysUser.setToken(generateToken);
				sysUser.setTokenCreateTime(tokenCreateTime);
				// 更新token
				sysUserBPO.modifyById(sysUser);

				Map<String,Object> bodyToken = new HashMap<String,Object>();
				bodyToken.put("token", generateToken);
				bodyToken.put("username", sysUser.getUsername());
				bodyToken.put("realName", sysUser.getRealName());
				bodyToken.put("userId", sysUser.getId());
				bodyToken.put("userType", sysUser.getUsertype());
				bodyToken.put("organCode", sysUser.getOrganCode());
				bodyToken.put("organName", sysUser.getOrganName());
				bodyToken.put("deptId", sysUser.getDeptId());
				retData.setRetBody(bodyToken);
				
			} catch (Exception e) {
				// 异常提示
				retData.getRetHead().setCode(WebRetCodeEnum.RET_CODE_0801004.getCode());
				retData.getRetHead().setMessage(WebRetCodeEnum.RET_CODE_0801004.getMessage());
			}
			clearAuthenticationAttributes(request);
			UfdmRequestUtil.addCsrfHeader(response);
			response.getWriter().write(JSON.toJSONString(retData));
		}

	}
}
